
import { ProTableProps, ActionType } from '@ant-design/pro-table'
import { Key, useRef, useState } from 'react';
export function useProTable<T = any, U = any>(
    type: 'checkbox' | 'radio' = 'checkbox',
    defaultSelectedRows: Key[] = []
) {
    const ref = useRef<ActionType>();
    const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>(defaultSelectedRows)
    const [selectedRows, setSelectedRows] = useState<T[]>([])
    const cbs: Function[] = [];
    const onChange = (cb: (keys: string[], rows: any[]) => void) => {
        cbs.push(cb)
    }
    const scbs: Function[] = [];
    const onSelect = (cb: (record: any, selected: boolean) => void) => {
        scbs.push(cb)
    }
    const props: ProTableProps<T, U> = {
        search: false,
        toolBarRender: false,
        actionRef: ref,
        rowSelection: {
            type: type,
            selectedRowKeys: selectedRowKeys,
            alwaysShowAlert: false,
            fixed: 'left',
            preserveSelectedRowKeys: true,
            onChange(selectedRowKeys, selectedRows, info) {
                setSelectedRowKeys(selectedRowKeys)
                setSelectedRows(selectedRows)
                cbs && cbs.map(cb => cb(selectedRowKeys, selectedRows));
            },
            onSelect(record, selected, rows, e) {
                scbs && scbs.map(cb => cb(record, selected))
            },
        }
    }
    return {
        props,
        actionRef: ref,
        selectedRowKeys,
        selectedRows,
        setSelectedRowKeys,
        setSelectedRows,
        onChange,
        onSelect
    }
}
